package com.yan.test.work.testpaging3

import android.content.Context
import androidx.paging.PagingSource
import androidx.paging.PagingState

class MainPagingDataSource(val ctx: Context, val keyWord:String) :PagingSource<Int, DataBean>(){
    override fun getRefreshKey(state: PagingState<Int, DataBean>): Int? {
        return state.anchorPosition?.let { position ->
            state.closestPageToPosition(position)?.prevKey?.plus(20)
                    ?: state.closestPageToPosition(position)?.nextKey?.minus(20)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, DataBean> {
        return try {
            val from = params.key ?: 0
            val next = from + 20

            val queryList = MainCenterApi().queryData(ctx, keyWord, from)
            LoadResult.Page(
                    data = queryList ,
                    prevKey = if(from == 0) null else (from - 20),
                    nextKey = next
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}